/**
 * 用户管理的用户关联的角色列表
 * @author linzongxue
 * @create_date 2012-1-30
 */
define(function(){
	var UserRolePanel = Ext.extend(Ext.grid.GridPanel, {
		height: 150,
		border: false,
		stripeRows: true,
	    enableHdMenu: false,
	    autoExpandColumn: 3,
        collapsible: false,
        split: true,
        autoScroll: true,
	    //loadMask: {msg: '正在加载数据...'},
		initComponent: function(){
			UserRolePanel.superclass.initComponent.call(Ext.apply(this, {
				tbar: au.permit([
					{xtype: 'label', text:'关联角色', style: 'font-weight:bold;margin-right:5px;'},
					'-',
	            	{text: '添加', permitId:'sys.user.addRole', handler: this.addRoles,scope: this, iconCls: 'icon-add', tooltip:'添加关联角色'},
	            	{text: '删除', permitId:'sys.user.removeRole', handler: this.removeRoles,scope: this, iconCls: 'icon-delete', tooltip:'删除关联角色'},
					'-',
					{text: '刷新', handler: this.refresh, scope: this, iconCls: 'icon-refresh'},
					'->',
					{xtype: 'label', name:'curUser', text:'未选择用户'}, //显示用户名称
					'-'
	            ]),
	            store: new Ext.data.JsonStore({
					fields: ['name', 'memo'],
					url: 'sys/user/getRolesOfUser.do'
				}),
				columns: [
					new Ext.grid.RowNumberer(),
				    this.sm = new Ext.grid.CheckboxSelectionModel(),
					{header: '角色名称', width: 200, dataIndex: 'name'},
					{header: '备注', width: 150, dataIndex: 'memo'}
				]
			}));
		},
		user: null, //当前选中的用户
		refresh: function(){
			if (this.user){
				this.store.load({params:{userId: this.user.id}});
			}
			else{
				this.store.removeAll();
			}
		},
		changeUser: function(user){
			this.user = user;
			var userLabel = this.getTopToolbar().find('name', 'curUser')[0];
			userLabel.setText(user ? '当前用户：' + user.name : '未选择用户');
			this.refresh();
		},
		addRoles: function(){
			if (!this.user){
				cu.hint('请先选择一个用户');
				return;
			}
			use('sys.user.SelectRoleWindow', function(Win){
				new Win({
					user: this.user,
					callback: function(roleIds){
						cu.post({
							url: 'sys/user/addRolesToUser.do',
							params: {userId: this.user.id, roleIds: roleIds},
							success: function(){
								this.refresh();
							},
							scope: this
						});
					},
					cbScope: this
				}).show();
			}, this);
		},
		removeRoles: function(){
			var records = this.getSelectionModel().getSelections();
			if (records.length == 0){
				cu.hint('请选择要删除关联的角色');
				return;
			}
			var msg = '确定要删除选中的' + records.length + '个关联角色吗？';
			cu.confirm(msg, function(){
				cu.post({
					url: 'sys/user/removeRolesFromUser.do',
					params: {userId: this.user.id, roleIds: lu.pluck(records, 'id')},
					success: function(){
						this.getStore().remove(records);
					},
					scope: this
				});
			}, this);
		}
	});
	return UserRolePanel;
});